package com.hua.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hua.pojo.Food;
import com.hua.pojo.User;
import com.hua.mapper.UserMapper;
import com.hua.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hua.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author hua
 * @since 2023-12-24
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    //JWT
    @Autowired
    private JwtUtils jwtUtils;

    //判断登录和是否注册了
    @Override
    public Map<String, Object> login(String username, String password) {

        //账户条件查询
        LambdaQueryWrapper<User> wrapper=new LambdaQueryWrapper<>();
        //添加查询条件
        wrapper.eq(User::getUsername,username);

        //账户和密码条件查询
        LambdaQueryWrapper<User> wrapper2=new LambdaQueryWrapper<>();
        //添加查询条件
        wrapper2.eq(User::getUsername,username);
        wrapper2.eq(User::getPassword,password);

        //执行查询
        User users =   this.baseMapper.selectOne(wrapper);
        //执行查询
        User users2 =  this.baseMapper.selectOne(wrapper2);

        //把数据封装到map集合，data返回数据
        Map<String, Object> data = new HashMap<>();

        //①账户不存在
        if(users==null){
            data.put("noHasThisAccount","true");
        }//账号存在
        else{
            //②账号存在，密码不正确
            if(users2==null){
                data.put("noHasThisAccount","false");//存在该账号
                data.put("access","false");          //密码验证不通过
            }else{ //③账号存在，密码正确
                data.put("noHasThisAccount","false");//存在该账号
                data.put("access","true");          //密码验证通过
                data.put("userInfo",users2);        //该登录的用户信息

                users2.setPassword(null);//密码不放进jwt
                String token=jwtUtils.createToken(users2);//生成jwt令牌
                data.put("token",token);            //token
            }

        }


        return data;

    }

    /**
     * 生成一个范围在 1000 到 9999 之间的随机数
     * @return
     */
    private static int generateRandomNumber() {
        Random random = new Random();
        return random.nextInt(9000) + 1000;
    }
    /**
     * 注册请求，首先要判断该账号是否存在
     * @param username
     * @param password
     * @return
     */
    @Override
    public Map<String, Object> register(String username, String password) {
        //账户条件查询
        LambdaQueryWrapper<User> wrapper=new LambdaQueryWrapper<>();
        //添加查询条件
        wrapper.eq(User::getUsername,username);
        //执行查询
        User userId = this.baseMapper.selectOne(wrapper);


        //把数据封装到map集合，data返回数据
        Map<String, Object> data = new HashMap<>();
        //该账号已经存在
        if(userId!=null){
            data.put("access","false");
        }else{//该账号为新账号，执行注册
            User newUser = new User();
            newUser.setUsername(username);//①账号
            newUser.setPassword(password);//②密码

            newUser.setNickname("用户");//③随机生成用户昵称
            // 生成随机数字
            int randomNumber = generateRandomNumber();
            // 将随机数字拼接到用户昵称后面
            String finalNickname = newUser.getNickname() + randomNumber;
            newUser.setNickname(finalNickname);

            newUser.setAvatarUrl("https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png");//注册时默认的头像

            newUser.setPermission(1);//普通游客默认权限是1

            int i = this.baseMapper.insert(newUser);

            if(i==1){//如果返回1，表示注册成功
                data.put("access","true");
            }else{
                data.put("access","error");//表示发生异常
            }
        }
        return data;
    }

    /**
     * 用户信息修改
     * @param user
     * @return
     */
    @Override
    public Map<String, Object> userInfoModify(User user) {
        int i = this.baseMapper.updateById(user);
        //
        Map<String, Object> data = new HashMap<>();
        if(i==1){
            data.put("data","修改成功！");
            return data;
        }else{
            return null;
        }
    }

    //密码更改
    //检测id和旧密码查询是否相对应
    @Override
    public int check(Integer id, String oldPassword) {

        //账户条件查询
        LambdaQueryWrapper<User> wrapper=new LambdaQueryWrapper<>();
        //添加查询条件
        wrapper.eq(User::getPassword,oldPassword);
        wrapper.eq(User::getId,id);
        //执行查询
        User user = this.baseMapper.selectOne(wrapper);

        if(user==null){//旧密码不对
            return -1;
        }else{
            return 1;
        }
    }

    //②进行密码修改
    @Override
    public int change(Integer id, String newPassword) {
        User user=new User();
        user.setId(id);
        user.setPassword(newPassword);

        int i = this.baseMapper.updateById(user);

        return i;
    }
}
